<template>
    <div class="min-h-screen bg-gray-50">
      <!-- 页面头部 -->
      <header class="bg-white shadow-sm">
        <div class="container mx-auto px-4 py-6">
          <h1 class="text-3xl font-bold text-gray-900">编程项目</h1>
          <p class="text-gray-600 mt-1">通过实战项目提升你的编程能力</p>
        </div>
      </header>
  
      <!-- 主要内容区 -->
      <main class="container mx-auto px-4 py-6">
        <!-- 筛选和搜索区域 -->
        <div class="bg-white rounded-lg shadow-sm p-4 mb-6 border border-gray-100">
          <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div class="flex flex-wrap items-center gap-3">
              <button class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                全部项目
              </button>
              <button class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                进行中
              </button>
              <button class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                已完成
              </button>
            </div>
          </div>
        </div>

      <!-- 搜索和筛选 -->
      <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg p-6 mb-8 border border-white/20">
        <div class="flex flex-col md:flex-row gap-4">
          <div class="flex-1">
            <div class="relative">
              <input
                v-model="searchQuery"
                @input="handleSearch"
                type="text"
                placeholder="搜索项目..."
                class="w-full pl-10 pr-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
              />
              <svg class="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
              </svg>
            </div>
          </div>
          <div class="flex gap-3">
            <select
              v-model="typeFilter"
              @change="handleFilter"
              class="px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
            >
              <option value="all">所有类型</option>
              <option value="web">Web项目</option>
              <option value="mobile">移动应用</option>
              <option value="desktop">桌面应用</option>
              <option value="other">其他</option>
            </select>
            <select
              v-model="difficultyFilter"
              @change="handleFilter"
              class="px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
            >
              <option value="all">所有难度</option>
              <option value="beginner">初级</option>
              <option value="intermediate">中级</option>
              <option value="advanced">高级</option>
            </select>
            <select
              v-model="sortBy"
              @change="handleFilter"
              class="px-4 py-3 bg-white/70 border border-gray-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
            >
              <option value="latest">最新</option>
              <option value="popular">最受欢迎</option>
              <option value="likes">最多点赞</option>
            </select>
          </div>
        </div>
      </div>

      <!-- 项目统计 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg p-6 hover:shadow-xl transition-all duration-300 transform hover:scale-105 border border-white/20">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-12 h-12 bg-gradient-to-r from-blue-500 to-blue-600 rounded-xl flex items-center justify-center shadow-lg">
                <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600">总项目数</p>
              <p class="text-3xl font-bold text-gray-900">{{ stats.totalProjects }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg p-6 hover:shadow-xl transition-all duration-300 transform hover:scale-105 border border-white/20">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-12 h-12 bg-gradient-to-r from-green-500 to-green-600 rounded-xl flex items-center justify-center shadow-lg">
                <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path>
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600">总点赞数</p>
              <p class="text-3xl font-bold text-gray-900">{{ stats.totalLikes }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg p-6 hover:shadow-xl transition-all duration-300 transform hover:scale-105 border border-white/20">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-12 h-12 bg-gradient-to-r from-purple-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg">
                <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z"></path>
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600">活跃用户</p>
              <p class="text-3xl font-bold text-gray-900">{{ stats.activeUsers }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg p-6 hover:shadow-xl transition-all duration-300 transform hover:scale-105 border border-white/20">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-12 h-12 bg-gradient-to-r from-orange-500 to-orange-600 rounded-xl flex items-center justify-center shadow-lg">
                <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"></path>
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-600">今日新增</p>
              <p class="text-3xl font-bold text-gray-900">{{ stats.todayProjects }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 项目列表 -->
      <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg border border-white/20">
        <div class="p-6 border-b border-gray-200/50">
          <div class="flex justify-between items-center">
            <h2 class="text-xl font-semibold text-gray-900">项目列表</h2>
            <button
              @click="openCreateProjectModal"
              class="px-4 py-2 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-lg hover:from-blue-700 hover:to-purple-700 transition-all duration-200 shadow-lg hover:shadow-xl"
            >
              <svg class="w-4 h-4 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
              </svg>
              分享项目
            </button>
          </div>
        </div>

        <div class="p-6">
          <!-- 加载状态 -->
          <div v-if="loading" class="flex justify-center items-center py-12">
            <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
            <span class="ml-3 text-gray-600">加载中...</span>
          </div>

          <!-- 项目网格 -->
          <div v-else-if="projects.length > 0" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div
              v-for="project in projects"
              :key="project.id"
              class="bg-white/90 backdrop-blur-sm rounded-xl border border-gray-200/50 shadow-sm hover:shadow-md transition-all duration-200 overflow-hidden group cursor-pointer"
              @click="viewProjectDetail(project)"
            >
              <!-- 项目封面 -->
              <div class="aspect-w-16 aspect-h-9 bg-gray-100 relative overflow-hidden">
                <img
                  v-if="project.cover_image"
                  :src="project.cover_image"
                  :alt="project.title"
                  class="w-full h-48 object-cover group-hover:scale-105 transition-transform duration-300"
                />
                <div
                  v-else
                  class="w-full h-48 bg-gradient-to-br from-gray-100 to-gray-200 flex items-center justify-center"
                >
                  <svg class="w-12 h-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
                  </svg>
                </div>
                
                <!-- 项目状态标签 -->
                <div class="absolute top-3 left-3">
                  <span
                    :class="[
                      'px-2 py-1 text-xs font-medium rounded-full',
                      project.status === 'approved' ? 'bg-green-100 text-green-800' :
                      project.status === 'pending' ? 'bg-yellow-100 text-yellow-800' :
                      'bg-gray-100 text-gray-800'
                    ]"
                  >
                    {{ project.status === 'approved' ? '已发布' : 
                       project.status === 'pending' ? '审核中' : '草稿' }}
                  </span>
                </div>
              </div>

              <!-- 项目信息 -->
              <div class="p-4">
                <div class="flex items-center space-x-2 mb-3">
                  <span class="px-2 py-1 bg-blue-100 text-blue-800 text-xs font-medium rounded-full">
                    {{ project.type }}
                  </span>
                  <span
                    :class="[
                      'px-2 py-1 text-xs font-medium rounded-full',
                      project.difficulty === 'beginner' ? 'bg-green-100 text-green-800' :
                      project.difficulty === 'intermediate' ? 'bg-yellow-100 text-yellow-800' :
                      'bg-red-100 text-red-800'
                    ]"
                  >
                    {{ project.difficulty === 'beginner' ? '初级' : 
                       project.difficulty === 'intermediate' ? '中级' : '高级' }}
                  </span>
                </div>

                <h3 class="font-semibold text-gray-900 mb-2 line-clamp-2">{{ project.title }}</h3>
                <p class="text-sm text-gray-600 mb-4 line-clamp-2">{{ project.description }}</p>

                <!-- 技术栈 -->
                <div class="flex flex-wrap gap-1 mb-4">
                  <span
                    v-for="tech in project.tech_stack?.slice(0, 3)"
                    :key="tech"
                    class="px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded"
                  >
                    {{ tech }}
                  </span>
                  <span
                    v-if="project.tech_stack?.length > 3"
                    class="px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded"
                  >
                    +{{ project.tech_stack.length - 3 }}
                  </span>
                </div>

                <!-- 项目统计 -->
                <div class="flex items-center justify-between text-sm text-gray-500">
                  <div class="flex items-center space-x-4">
                    <div class="flex items-center">
                      <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path>
                      </svg>
                      {{ project.like_count || 0 }}
                    </div>
                    <div class="flex items-center">
                      <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                      </svg>
                      {{ project.view_count || 0 }}
                    </div>
                  </div>
                  <div class="flex items-center">
                    <img
                      :src="project.author.avatar_url || '/static/avatar/default.jpg'"
                      :alt="project.author.username"
                      class="w-5 h-5 rounded-full mr-2"
                    />
                    <span>{{ project.author.username }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 空状态 -->
          <div v-else class="text-center py-12">
            <div class="w-16 h-16 mx-auto mb-4 bg-gray-100 rounded-full flex items-center justify-center">
              <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
              </svg>
            </div>
            <h3 class="text-lg font-medium text-gray-900 mb-2">暂无项目</h3>
            <p class="text-gray-500 mb-4">还没有人分享项目，成为第一个分享者吧</p>
            <button
              @click="openCreateProjectModal"
              class="px-4 py-2 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-lg hover:from-blue-700 hover:to-purple-700 transition-all duration-200"
            >
              分享第一个项目
            </button>
          </div>

          <!-- 分页 -->
          <div v-if="projects.length > 0 && totalPages > 1" class="mt-8 flex justify-center">
            <nav class="flex items-center space-x-2">
              <button
                @click="goToPage(currentPage - 1)"
                :disabled="currentPage === 1"
                class="px-3 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                上一页
              </button>
              
              <button
                v-for="page in visiblePages"
                :key="page"
                @click="goToPage(page)"
                :class="[
                  'px-3 py-2 text-sm font-medium rounded-lg',
                  page === currentPage
                    ? 'bg-blue-600 text-white'
                    : 'text-gray-500 bg-white border border-gray-300 hover:bg-gray-50'
                ]"
              >
                {{ page }}
              </button>
              
              <button
                @click="goToPage(currentPage + 1)"
                :disabled="currentPage === totalPages"
                class="px-3 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                下一页
              </button>
            </nav>
          </div>
        </div>
      </div>
      </main>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { projectApi } from '@/api/project'

// 简单的防抖函数
const debounce = (func: Function, delay: number) => {
  let timeoutId: number
  return (...args: any[]) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => func.apply(null, args), delay)
  }
}

// 响应式数据
const loading = ref(false)
const projects = ref<any[]>([])
const searchQuery = ref('')
const typeFilter = ref('all')
const difficultyFilter = ref('all')
const sortBy = ref('latest')
const currentPage = ref(1)
const pageSize = ref(12)
const totalPages = ref(1)

const stats = ref({
  totalProjects: 0,
  totalLikes: 0,
  activeUsers: 0,
  todayProjects: 0
})

// 计算属性
const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
})

// 方法
const loadProjects = async () => {
  try {
    loading.value = true
    const response = await projectApi.getProjects({
      page: currentPage.value,
      page_size: pageSize.value,
      search: searchQuery.value || undefined,
      type: typeFilter.value !== 'all' ? typeFilter.value : undefined,
      difficulty: difficultyFilter.value !== 'all' ? difficultyFilter.value : undefined,
      sort: sortBy.value
    })
    
    if (response.data) {
      projects.value = response.data.data || []
      totalPages.value = response.data.total_pages || 1
    }
  } catch (error) {
    console.error('加载项目列表失败:', error)
  } finally {
    loading.value = false
  }
}

const loadStats = async () => {
  try {
    const response = await projectApi.getProjectStats()
    if (response.data) {
      stats.value = {
        totalProjects: response.data.total_projects,
        totalLikes: response.data.total_likes,
        activeUsers: response.data.active_users,
        todayProjects: response.data.today_projects
      }
    }
  } catch (error) {
    console.error('加载项目统计失败:', error)
  }
}

const handleSearch = debounce(() => {
  currentPage.value = 1
  loadProjects()
}, 500)

const handleFilter = () => {
  currentPage.value = 1
  loadProjects()
}

const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    loadProjects()
  }
}

const viewProjectDetail = (project: any) => {
  // 跳转到项目详情页面
  console.log('查看项目详情:', project)
  // router.push(`/project/${project.id}`)
}

const openCreateProjectModal = () => {
  // 打开创建项目模态框或跳转到创建页面
  console.log('打开创建项目模态框')
  // router.push('/create-project')
}

onMounted(async () => {
  await Promise.all([
    loadProjects(),
    loadStats()
  ])
})
</script>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.aspect-w-16 {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 */
}

.aspect-w-16 > * {
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
</style>